<template>
  <view>
    <view id="content" :class="{ ellipsis: lines < _lines && showOpen }">
      {{ _lines }}{{ text }}
      <text
        @click="showOpen = false"
        v-if="lines < _lines && showOpen"
        class="open"
        >...展开</text
      >
    </view>
    <view id="one-line">{{ text }}</view>
  </view>
</template>
<script>
export default {
  props: {
    text: "",
    lines: {
      type: Number,
      default: 3,
    },
  },
  data() {
    return {
      textHeight: 0,
      oneHeight: 0,
      showOpen: true,
    };
  },
  computed: {
    _lines() {
      let line = Math.floor(
        this.textHeight > 0 && this.oneHeight > 0
          ? this.textHeight / this.oneHeight
          : 0
      );
      return line;
    },
  },
  methods: {
    getQyjsHeight() {
      let that = this;
      const query = uni.createSelectorQuery().in(this);
      query
        .select("#content")
        .fields(
          {
            size: true,
          },
          (data) => {
            that.textHeight = data.height;
          }
        )
        .exec();

      //获取单行文本高度
      query
        .select("#one-line")
        .fields(
          {
            size: true,
          },
          (data) => {
            that.oneHeight = data.height;
          }
        )
        .exec();
    },
  },
  mounted() {
    this.getQyjsHeight();
  },
};
</script>
<style lang="scss" scoped>
#content {
  position: relative;
}
#one-line {
  opacity: 0;
  white-space: nowrap;
  position: fixed;
  z-index: -100;
}
.ellipsis {
  -webkit-line-clamp: 3;
}
.open {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: #fff;
  color: #757575;
  padding-left: 20rpx;
}
</style>
